package com.bw.controller.technology;


import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.material.PiMaterial;
import com.bw.entity.process.PiProcess;
import com.bw.entity.technology.*;
import com.bw.entity.user.TbUser;
import com.bw.resp.ResponseResult;
import com.bw.service.material.IPiMaterialService;
import com.bw.service.process.IPiProcessService;
import com.bw.service.technology.*;
import com.bw.utils.IdWorker;
import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhouxin
 * @since 2020-06-22
 */
@CrossOrigin
@RestController
@RequestMapping("order")
public class PiOrderController {

    @Autowired
    private IPiOrderService orderService;

    @Autowired
    private IPiOrderItemService orderItemService;

    @Autowired
    private IPiOrderLogService orderLogService;

    @Autowired
    private IPiOrderItemMaterialService materialService;

    @Autowired
    private IPiOrderItemProcessService processService;

    @Autowired
    private IPiMaterialService iPiMaterialService;

    @Autowired
    private IPiProcessService iPiProcessService;

    private final Logger logger = LoggerFactory.getLogger(PiOrderController.class);

    public static void main(String[] args) {
        IdWorker idWorker = new IdWorker(0, 0,0);
        long id = idWorker.nextId();
        System.out.println(id);
    }

    @PostMapping("getTechnologyList/{pagenum}/{pagesize}")
    public ResponseResult getTechnologyList(@RequestBody PiOrder order,@PathVariable("pagenum") Integer currentPage,@PathVariable("pagesize")Integer pageSize){
        ResponseResult result = ResponseResult.SUCCESS();
        PageHelper.startPage(currentPage,pageSize);
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            if (order.getCode()!=null){
                queryWrapper.like("code",order.getCode());
            }
            if (order.getLinkmanName()!=null){
                queryWrapper.like("linkmanName",order.getLinkmanName());
            }
            queryWrapper.between("state",1,2);
            List<PiOrder> list = orderService.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setSuccess(true);
            result.setMessage("查询成功!");
            result.setResult(pageInfo);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败!");
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping("UpdateStats/{id}")
    public ResponseResult UpdateStats(@PathVariable("id") Long id, HttpSession session, HttpServletRequest request){
        logger.info("开始转工艺");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder1 = orderService.getById(id);
            PiOrderLog log = new PiOrderLog();
            String token = request.getHeader("token");
            PublicKey publicKey = RsaUtils.getPublicKey("C:\\1711A\\keys\\rsa.pub");
            UserInfo userInfo =   JwtUtils.getInfoFromToken(token,publicKey);
            String username = userInfo.getUsername();
            log.setUserName(username);
            log.setOrderId(Long.valueOf(piOrder1.getCode()));
            log.setRemarks("工艺(工艺员)");
            log.setTbId(id);
            orderLogService.saveOrUpdate(log);
            PiOrder order = orderService.getById(id);
            PiOrder piOrder = order.setState(2);
            order.setUpdateDate(new Date());
            TbUser user = (TbUser) session.getAttribute("user");
            orderService.saveOrUpdate(piOrder);
            result.setMessage("转工艺成功!");
            logger.info("工艺成功!");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("转工艺失败!"+e.toString());
        }
        return result;
    }

    @PostMapping("LookById/{id}")
    public ResponseResult LookById(@PathVariable("id") Long id){
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("开始查询BOM详情");
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            if (id!=null){
                queryWrapper.eq("orderid",id);
            }
            List<PiOrderItem> list = orderItemService.list(queryWrapper);
            result.setResult(list);
            result.setMessage("查询成功!");
            result.setSuccess(true);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败!"+e.toString());
            logger.error("查询失败!"+e.toString());
        }
        logger.info("查询成功!");
        return result;
    }

    @PostMapping("getTenById/{oid}")
    public ResponseResult getTenById(@PathVariable("oid") Long oid){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder order = orderService.getById(oid);
            result.setResult(order.getState());
        }catch (Exception e){
            result.setMessage("查询失败!"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("getMeList/{id}")
    public ResponseResult getMeList(@PathVariable("id") Long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrderItem orderItem = orderItemService.getById(id);
            result.setResult(orderItem);
        }catch (Exception e){
            result.setMessage("查询失败!"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("getOrderDetail/{id}")
    public ResponseResult getOrderDetail(@PathVariable("id") Long id){
        logger.info("开始查询日志信息");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            if (id!=null){
                queryWrapper.eq("tb__ID",id);
            }
            List list = orderLogService.list(queryWrapper);
            result.setResult(list);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败!"+e.toString());
        }
        return result;
    }

    private int i = 1;
    @PostMapping("addMeAndProcess/{id}/{oid}")
    public ResponseResult addMeAndProcess(HttpServletRequest request,@PathVariable("id") Long id,@PathVariable("oid") Long oid, @RequestBody OrderItemMaterialAndProcess orderItemMaterialAndProcess){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            List<PiOrderItemMaterial> piOrderItemMaterialList = orderItemMaterialAndProcess.getPiOrderItemMaterialList();
            for (PiOrderItemMaterial orderItemMaterial : piOrderItemMaterialList){
                Long id1 = orderItemMaterial.getMaterialId();
                PiMaterial material = iPiMaterialService.getById(id1);
                PiOrderItem orderItem = orderItemService.getById(id);
                Integer num = orderItem.getNum();
                BigDecimal bigDecimal1 = new BigDecimal(num);
                BigDecimal price = material.getPrice();
                Double weight =orderItemMaterial.getAfWeight();
                BigDecimal bigDecimal = new BigDecimal(weight);
                BigDecimal multiply = price.multiply(bigDecimal);
                orderItemMaterial.setMaterCost(multiply.multiply(bigDecimal1));
                orderItemMaterial.setOrderItemId(id);
            }
            List<PiOrderItemProcess> piOrderItemProcessList = orderItemMaterialAndProcess.getPiOrderItemProcessList();
            for (PiOrderItemProcess orderItemProcess : piOrderItemProcessList){
                orderItemProcess.setOrderItemId(id);
                orderItemProcess.setSn(i++);
                Double hour = orderItemProcess.getPreWorkHour();
                Long processId = orderItemProcess.getProcessId();
                PiProcess process = iPiProcessService.getById(processId);
                    logger.info("开始按时间收费");
                    BigDecimal prePrice = process.getPrePrice();
                    BigDecimal bigDecimal = new BigDecimal(hour);
                    BigDecimal multiply = prePrice.multiply(bigDecimal);
                    orderItemProcess.setPreCost(multiply);
                    PiOrderItem orderItem = orderItemService.getById(id);
                    Integer num = orderItem.getNum();
                    BigDecimal decimal = new BigDecimal(num);
                    orderItemProcess.setProCost(decimal.multiply(prePrice));
            }
            materialService.saveOrUpdateBatch(piOrderItemMaterialList);
            processService.saveOrUpdateBatch(piOrderItemProcessList);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("orderId",oid);
            //获取该订单的零件列表 进行循环
            List<PiOrderItem> list = orderItemService.list(queryWrapper);
            //循环零件列表
            for (int j=0;j<list.size();j++){
                //获取订单零件订单id
                Long orderIditem = list.get(j).getId();
                //获取零件订单的工序和原材料的id，查询价格
                QueryWrapper wrapper = new QueryWrapper();
                //将id方法到数据中进行查询原材料的数据价格等
                wrapper.eq("orderItemId",orderIditem);
                List<PiOrderItemMaterial> materialList = materialService.list(wrapper);
                int pirceMater = 0;
                int pirceProcess = 0;
                BigDecimal bigDecimal = new BigDecimal(pirceMater);
                for (PiOrderItemMaterial material:materialList) {
                    bigDecimal= bigDecimal.add(material.getMaterCost());
                }
                List<PiOrderItemProcess> list1 = processService.list(wrapper);
                BigDecimal processPrice = new BigDecimal(pirceProcess);
                for (PiOrderItemProcess process:list1) {
                    processPrice = processPrice.add(process.getPreCost().add(process.getProCost()));
                }
                BigDecimal priceAll = processPrice.add(bigDecimal);
                PiOrderItem orderItem = orderItemService.getById(id);
                orderItem.setPrice(priceAll);
                orderItemService.saveOrUpdate(orderItem);
                int orderPriceAll=0;
                BigDecimal orderPriceAllBig = new BigDecimal(orderPriceAll);
                for (int c=0;c<list.size();c++){
                        orderPriceAllBig = orderPriceAllBig.add(list.get(c).getPrice());
                }
                int b=0;
                if (b==0){
                    PiOrder order = orderService.getById(orderIditem);
                    order.setPrice(orderPriceAllBig);
                    BigDecimal TaxPrice = orderPriceAllBig.add(orderPriceAllBig.multiply(order.getTaxRate()));
                    order.setPriceIt(TaxPrice);
                    String token = request.getHeader("token");//获取token
                    PublicKey publicKey = RsaUtils.getPublicKey("C:\\1711A\\keys\\rsa.pub");
                    UserInfo userInfo =   JwtUtils.getInfoFromToken(token,publicKey);
                    Long gid = userInfo.getId();
                    order.setUpdateDate(new Date());
                    order.setTechnologyDate(new Date());
                    order.setTechnicianId(gid);
                    order.setUpdateUser(gid);
                    orderService.saveOrUpdate(order);
                    b++;
                }

            }
            result.setSuccess(true);
        }catch (Exception e){
            result.setMessage("添加失败!"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("getMeAndProcessList/{id}")
    public ResponseResult getMeAndProcessList(@PathVariable("id") Long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            if (id!=null){
                queryWrapper.eq("orderItemId",id);
            }
            List<PiOrderItemMaterial> list = materialService.list(queryWrapper);
            List<PiOrderItemProcess> list1 = processService.list(queryWrapper);
            OrderItemMaterialAndProcess orderItemMaterialAndProcess = new OrderItemMaterialAndProcess();
            orderItemMaterialAndProcess.setPiOrderItemMaterialList(list);
            orderItemMaterialAndProcess.setPiOrderItemProcessList(list1);
            result.setResult(orderItemMaterialAndProcess);
            result.setMessage("查询成功!");
        }catch (Exception e){
            result.setMessage("查询失败！");
            result.setSuccess(false);
        }
        return result;
    }

}
